package com.health.controller;

/**
 * @Description
 * @Author konglz
 * @Data 2023/3/27 10:04
 */


import com.health.common.Result;
import com.health.constant.RedisConstant;
import com.health.util.AliyunUploadUtils;
import com.health.util.QiNiuUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传")
public class UploadController extends BaseController{

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile file) throws IOException {
        // 1. 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2. 重新设置文件的名称
        String uuid = UUID.randomUUID().toString();
        // 文件的名称 = uuid + 源文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid + substring;
        fileName.replaceAll("-", "");
        // 3. 调用图片上传的工具类
        QiNiuUploadUtils.uploadFile(file.getBytes(), fileName);
        // 将上传的图片名称保存到Redis中
        stringRedisTemplate.opsForSet().add(RedisConstant.REDIS_ALL_UPLOAD_IMAGE, fileName);
        // 4. 响应数据
        return dataResult(fileName);
    }

    @ApiOperation("文件上传")
    @PostMapping("/aliyunUpload")
    public Result aliyunUpload(@RequestPart MultipartFile file) throws IOException {
        // 1. 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 2. 重新设置文件的名称
        String uuid = UUID.randomUUID().toString();
        // 文件的名称 = uuid + 源文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid + substring;
        fileName.replaceAll("-", "");
        // 3. 调用图片上传的工具类
        AliyunUploadUtils.upload(file.getBytes(), fileName);
        stringRedisTemplate.opsForSet().add(RedisConstant.REDIS_ALL_UPLOAD_IMAGE, fileName);
        // 4. 响应数据
        return dataResult(fileName);
    }

    @ApiOperation("七牛云删除图片")
    @GetMapping("/delete")
    public Result delete(String fileName){
        QiNiuUploadUtils.deleteFile(fileName);
        return success();
    }

    @ApiOperation("阿里云删除图片")
    @GetMapping("/aliyunDeleteImage")
    public Result delete2(String fileName){
        AliyunUploadUtils.deleteImg(fileName);
        return success();
    }
}
